/*
 * @ author madman 
 * @ use 用户及相关接口逻辑层
 */
import md5 from 'md5';
const AdminModel = require('../../models/system/admin.model');
const PermissionsModel = require('../../models/system/permissions.model');
const Utils = require('../utils');
class AdminController {
    //递归分类树静态方法
    static getTree(arr, id) {
        var tree = []
        arr.map(item => {
            if (item.parentId === id && item.level !== '3') {
                tree.push({
                    _id: item._id,
                    name: item.name,
                    parentId: item.parentId,
                    icon: item.icon,
                    routerUrl: item.routerUrl,
                    routerParameter: item.routerParameter,
                    routerParameterDescribe: item.routerParameterDescribe,
                    routerName: item.routerName,
                    routerDescribe: item.routerDescribe,
                    isMenu: item.isMenu,
                    isChild: item.isChild,
                    children: AdminController.getTree(arr, item._id)
                })
            }
        })
        return tree
    }
    // 用户登录
    async login(ctx) {
        const { username, password } = ctx.request.body;
        if (!username || !password) {
            return ctx.error({ msg: '获取用户失败!' });
        }
        const data = await AdminModel.findOne({ username, password: md5(password) }, { password: 0 });
        if (!data) {
            return ctx.error({ msg: '用户名或密码错误!' });
        }

        ctx.session.user = data;
        const token = await Utils.createToken();
        ctx.cookies.set('user_id', data.id, { maxAge: 86400000, httpOnly: false });
        ctx.cookies.set('token', token, { maxAge: 86400000, httpOnly: false });
        ctx.success({ msg: '登录成功', data: { uid: data.id, username: data.username } });
    }
    // 用户退出
    async logout(ctx) {
        const userid = ctx.query.uid;
        const cookie_userid = ctx.cookies.get('userid');
        if (!userid) {
            return ctx.error({ msg: '用户id不存在!' });
        }

        const user = ctx.session.user;
        if (!user && !cookie_userid) {
            return ctx.error({ msg: '该用户已退出!' });
        }

        ctx.session.user = null;
        ctx.cookies.set('token', null);
        ctx.cookies.set('user_id', null);
        return ctx.success({ msg: '退出成功!' });
    }
    // 获取用户信息
    async getUserInfo(ctx) {
        let userid = ctx.query.uid;
        if (!userid) {
            return ctx.error({ msg: '用户id不能为空' });
        }
        const user = await AdminModel.findOne({ _id: userid.toString() }).populate('power')
        if (!user) {
            return ctx.error({ msg: '该用户不存在!' })
        }
        // console.log(user) // 关联角色的权限菜单
        const powerTree = await PermissionsModel.find({ _id: { $in: user.power.power } }).sort({ 'sort': 1 })
        const token = ctx.cookies.get('token')
        const tree = AdminController.getTree(powerTree, '-1')
        return ctx.success({
            data: {
                userInfo: {
                    uid: user.id,
                    rolesName: user.power.name,
                    name: user.username,
                    power: user.power.power
                },
                powerTree: tree,
                token: token
            }
        });
    }
    // 获取用户权限
    async getUserPower(ctx) {
        let userid = ctx.query.uid;
        if (!userid) {
            return ctx.error({ msg: '用户id不能为空' });
        }
        const user = await AdminModel.findOne({ _id: userid.toString() }).populate('power')
        if (!user) {
            return ctx.error({ msg: '该用户不存在!' })
        }
        return ctx.success({
            data: user.power.power
        });
    }
}

export default new AdminController;